package fr.obsmip.sedoo.client.ui.metadata.observatory;

import java.util.Iterator;
import java.util.List;

import org.gwtbootstrap3.client.ui.Alert;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

import fr.obsmip.sedoo.client.GlobalBundle;
import fr.obsmip.sedoo.client.ui.AbstractSection;
import fr.obsmip.sedoo.shared.api.IsObservatory;

public class ObservatoryEntryCreationViewImpl extends AbstractSection implements ObservatoryEntryCreationView {

	@UiField
	Alert noObservatoryToCreate;

	@UiField
	ListBox observatories;

	@UiField
	HorizontalPanel creationPanel;

	private static WelcomeViewImplUiBinder uiBinder = GWT
			.create(WelcomeViewImplUiBinder.class);

	private Presenter presenter;

	interface WelcomeViewImplUiBinder extends UiBinder<Widget, ObservatoryEntryCreationViewImpl> {
	}

	public ObservatoryEntryCreationViewImpl() {
		super();
		GWT.<GlobalBundle>create(GlobalBundle.class).css().ensureInjected();
		initWidget(uiBinder.createAndBindUi(this));
		applyCommonStyle();
		noObservatoryToCreate.setVisible(true);
		creationPanel.setVisible(false);
	}

	@Override
	public void setObservatories(List<IsObservatory> observatoryList) {
		if (observatoryList.isEmpty() == false)
		{
			observatories.clear();
			Iterator<IsObservatory> iterator = observatoryList.iterator();
			while (iterator.hasNext()) {
				IsObservatory current = iterator.next();
				observatories.addItem(current.getName());
			}
			creationPanel.setVisible(true);
			noObservatoryToCreate.setVisible(false);		
		}
		else
		{
			observatories.clear();
			creationPanel.setVisible(false);
			noObservatoryToCreate.setVisible(true);
		}
	}

	@UiHandler("createButton")
	void onCreateButtonClicked(ClickEvent event) {
		presenter.create(observatories.getItemText(observatories.getSelectedIndex()));
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

}
